#! /usr/bin/env python
#
# Prelude IRC ChatBot
# Cyberwolf <cyberwolf2000@gmx.net>
# 
# based on an example program using ircbot.py by
# Joel Rosdahl <joel@rosdahl.net>

"""Prelude IRC Chatbot.

This is an IRC chatbot that uses the SingleServerIRCBot class from
ircbot.py and interfaces to the mono version of prelude.
(http://prelude.lennart-lopin.de)
The bot enters a channel and listens for commands or messages
in private messages and channel traffic.  Commands in channel messages
are given by prefixing the text by the bot name followed by a colon.
It also responds to DCC CHAT invitations and echos data sent in such
sessions. When it is an unknown command it will be interpreted as a message
to the prelude chatbot and will be forwarded.

The known commands are:

    stats -- Prints some channel information.

    disconnect -- Disconnect the bot.  The bot will try to reconnect
                  after 60 seconds.

    die -- Let the bot cease to exist.

    dcc -- Let the bot invite you to a DCC CHAT connection.
"""

import string
from ircbot import SingleServerIRCBot
from irclib import nm_to_n, nm_to_h, irc_lower, ip_numstr_to_quad, ip_quad_to_numstr
import os
from time import time

class PreludeBot(SingleServerIRCBot):
    def __init__(self, channel, nickname, server, port=6667, password=None, learninterval=300):
        SingleServerIRCBot.__init__(self, [(server, port, password)], nickname, nickname)
        self.channel = channel
        self.start_prelude()
        self.time = time()
        self.learninterval = learninterval
        
    def start_prelude(self):
        (self.pipein, self.pipeout) = os.popen2("mono PreludinixCmd.exe");
        while string.strip(self.pipeout.readline()) != "Quit with 'quit'":
            pass

    def learn_prelude(self):
        print "learning"
        self.pipein.write("quit\n")
        self.pipein.flush()
        self.pipeout.close()
        self.pipein.close()
        print "restarting"
        self.start_prelude()
        print "started"
        
    def on_nicknameinuse(self, c, e):
        c.nick(c.get_nickname() + "_")

    def on_welcome(self, c, e):
        c.join(self.channel)

    def on_privmsg(self, c, e):
        self.do_command(e, e.arguments()[0])

    def on_pubmsg(self, c, e):
        a = string.split(e.arguments()[0], ":", 1)
        if len(a) > 1 and irc_lower(a[0]) == irc_lower(self.connection.get_nickname()):
            self.do_command(e, string.strip(a[1]))
        return

    def on_dccmsg(self, c, e):
        c.privmsg("You said: " + e.arguments()[0])

    def on_dccchat(self, c, e):
        if len(e.arguments()) != 2:
            return
        args = string.split(e.arguments()[1])
        if len(args) == 4:
            try:
                address = ip_numstr_to_quad(args[2])
                port = int(args[3])
            except ValueError:
                return
            self.dcc_connect(address, port)

    def do_command(self, e, cmd):
        nick = nm_to_n(e.source())
        if e.eventtype() == "pubmsg":
            nick = e.target()
        c = self.connection

        t = time()
        if (self.time + self.learninterval) < t:
            self.learn_prelude()
            c.notice(nick, "I automatically learned what we talked about. This happens every %d seconds."%(self.learninterval))
            self.time = t
        
        if cmd == "disconnect":
            self.disconnect()
        elif cmd == "die":
            self.die()
        elif cmd == "stats":
            for chname, chobj in self.channels.items():
                c.notice(nick, "--- Channel statistics ---")
                c.notice(nick, "Channel: " + chname)
                users = chobj.users()
                users.sort()
                c.notice(nick, "Users: " + string.join(users, ", "))
                opers = chobj.opers()
                opers.sort()
                c.notice(nick, "Opers: " + string.join(opers, ", "))
                voiced = chobj.voiced()
                voiced.sort()
                c.notice(nick, "Voiced: " + string.join(voiced, ", "))
        elif cmd == "dcc":
            dcc = self.dcc_listen()
            c.ctcp("DCC", nick, "CHAT chat %s %d" % (
                ip_quad_to_numstr(dcc.localaddress),
                dcc.localport))
        elif cmd == "quit":
            c.notice(nick, "Not understood: " + cmd)
        elif cmd == "learn":
            self.learn_prelude()
            c.notice(nick, "I learned what we talked about.")
        else:
            self.pipein.write(cmd+"\n")
            self.pipein.flush()
            line = self.pipeout.readline()
            answer = line.replace("You say: ", "", 1)
            answer = answer.replace("Prelude's reply: ", "", 1)
            c.privmsg(nick, answer)
        #    c.notice(nick, "Not understood: " + cmd)

def main():
    import sys
    if len(sys.argv) < 4:
        print "Usage: preludebot <server[:port]> <channel> <nickname> <password>"
        sys.exit(1)

    s = string.split(sys.argv[1], ":", 1)
    server = s[0]
    if len(s) == 2:
        try:
            port = int(s[1])
        except ValueError:
            print "Error: Erroneous port."
            sys.exit(1)
    else:
        port = 6667
    channel = sys.argv[2]
    nickname = sys.argv[3]
    password = sys.argv[4]

    bot = PreludeBot(channel, nickname, server, port, password)
    bot.start()

if __name__ == "__main__":
    main()
